package com.west.imserver.handler.impl;

import imserverentity.entity.IChattable;
import imserverentity.entity.Protocol;
import imserverentity.entity.impl.Client;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.west.imserver.handler.IHandler;
import com.west.imserver.sender.Sender;
import com.west.imserver.server.IMServer;

public class LoginHandler implements IHandler{
	private String msgType;
	private Map<String, Object> params;
	private ObjectOutputStream oos;
	
	public LoginHandler() {}
	public LoginHandler(String msgType, Map<String, Object> params, ObjectOutputStream oos) {
		this.msgType = msgType;
		this.params = params;
		this.oos = oos;
	}
	
	public String getMsgType() {
		return msgType;
	}
	public void setMsgType(String msgType) {
		this.msgType = msgType;
	}
	public ObjectOutputStream getOos() {
		return oos;
	}
	public void setOos(ObjectOutputStream oos) {
		this.oos = oos;
	}
	public void setParams(Map<String, Object> params) {
		this.params = params;
	}
	
	public void handle() throws IOException {
		IChattable from = (IChattable) params.get("from");
		IMServer.senders.put(from, oos);
		IMServer.clients.put(((Client)from).getAccount(), from);
		List<String> list = new ArrayList<String>(IMServer.clients.keySet());
		String msg = ((Client) from).getAccount() + " logins";
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("from", from);
		params.put("msg", msg);
		params.put("list", list);
		params.put("status", "200");
		Protocol protocol = new Protocol(msgType, params);
//		try {
//			Thread.sleep(1000);
//		} catch (InterruptedException e) {
//			e.printStackTrace();
//		}
		for(String account : list) {
			ObjectOutputStream ooss = IMServer.senders.get(IMServer.clients.get(account));
			Sender.send(protocol, ooss);
		}
	}
}
